package com.fbinggun.playeraddattribute;

import com.fbinggun.fattribute.data.EntityData;
import com.fbinggun.fbinggunutil.SqlUtil;
import com.fbinggun.sql.SQLite;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public final class PlayerAddAttribute extends JavaPlugin {
    public static SQLite sql;
    public static PlayerAddAttribute plugin;
    public static AttributeTabel tabel;
    public static Map<String,PlayerData> dataMap= new HashMap<>();
    @Override
    public void onEnable() {
        plugin=this;
        // Plugin startup logic
        saveDefaultConfig();
        reloadConfig();
        try {
            sql= SqlUtil.reloadSQL(this,getConfig().getConfigurationSection("SQL"));
            tabel=new AttributeTabel();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        EntityData.registerUpData(new UpPlayerAddAttribute());
        getCommand("PlayerAddAttribute").setExecutor(new Command());
        getCommand("PlayerAddAttribute").setTabCompleter(new Command());
        new BukkitRunnable() {
            @Override
            public void run() {
                for(PlayerData playerData:dataMap.values()){
                    try {
                        playerData.save();
                    } catch (SQLException e) {
                        throw new RuntimeException(e);
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }.runTaskTimerAsynchronously(this,500,500);
    }

    @Override
    public void onDisable() {
        for(PlayerData playerData:dataMap.values()){
            try {
                playerData.save();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
        // Plugin shutdown logic
    }
    public PlayerData getPlayerData(Player player) throws SQLException, ClassNotFoundException {
        if(dataMap.get(player.getName())==null){
            PlayerData playerData = tabel.getPlayerData(player.getName());
            dataMap.put(player.getName(),playerData);
            return playerData;
        }else {
            return dataMap.get(player.getName());
        }
    }
    public PlayerData getPlayerData(String player) throws SQLException, ClassNotFoundException {
        if(dataMap.get(player)==null){
            PlayerData playerData = tabel.getPlayerData(player);
            dataMap.put(player,playerData);
            return playerData;
        }else {
            return dataMap.get(player);
        }
    }
}
